﻿using System;
using System.Data.Common;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Dapper;
using Kele.Activity.Core;
using Kele.Activity.Models;
using Kele.Repository;
using MySql.Data.MySqlClient;

namespace Kele.Activity
{
    public class MerchantEngine
    {              protected readonly string _connectionString = AppConfig.Setting.DefaultConnectionString;
        protected static readonly Func<DbConnection> ConnectionFactory = () => new MySqlConnection(AppConfig.Setting.DefaultConnectionString);

        public async Task<dynamic> GetStoreList(int merchant_id, int skip, int take)
        {
            await using var connection = new MySqlConnection(_connectionString);
            var sql = new StringBuilder();
            sql.Append("SELECT * FROM kl_merchant_store WHERE id=@merchant_id ORDER BY id DESC ");
            if (take > 0) sql.Append(" LIMIT @take OFFSET @skip");
            sql.Append("; SELECT Count(*) FROM  kl_merchant_store where id=@merchant_id");

            using var multi = await connection.QueryMultipleAsync(sql.ToString(), new { merchant_id, skip, take });
            var data = multi.Read<MerchantStore>().ToList();
            var total = multi.ReadSingle<int>();
            return new { total, data };
        }

        public async Task UpdatePersonInfoAsync(Merchant merchant)
        {
            await using var connection = new MySqlConnection(_connectionString);
            const string sql = "update kl_merchant set `name`=@name, avatar=@avatar where id=@id";
            await connection.ExecuteAsync(sql, new { merchant.name, merchant.id, merchant.avatar });
        }

        public static async Task<Merchant> GetMerchantAsync(int id)
        {
            var key = string.Format(AppCache.MERCHANT, id);
            var ret = await AppCache.CacheStrategy.GetAsync<Merchant>(key);
            if (ret != null) return ret;

            var sql = new StringBuilder();
            sql.Append(" select * from kl_merchant where id = @id; ")
               .Append(" select * from kl_merchant_store where merchant_id = @id; ");

            await using var connection = ConnectionFactory();
            using var multi = await connection.QueryMultipleAsync(sql.ToString(), new { id });
            
            ret = multi.ReadSingleOrDefault<Merchant>();
            ret.stores = multi.Read<MerchantStore>().ToList();
            await AppCache.CacheStrategy.SetAsync(key, ret);
            return ret;
        }

        public async Task<dynamic> GetInfoAsync(int merchant_id)
        {
            using (var connection = new MySqlConnection(_connectionString))
            {
                var sql = "SELECT * FROM kl_merchant WHERE id=@merchant_id;";
                var merchant = await connection.QueryFirstOrDefaultAsync<Merchant>(sql, new { merchant_id });
                if (merchant == null) throw new Exception("没有找到商家信息");
                var agentId = merchant.agent_id;
                sql = " SELECT  * FROM  kl_agent where id=@agentId; select * from kl_agent_service where agent_id=@agentId";
                Agent agent;
                using (var multi = await connection.QueryMultipleAsync(sql, new { agentId }))
                {
                    agent = multi.Read<Agent>().FirstOrDefault();
                    var agentServices = multi.Read<AgentService>().ToList();
                    if (agent != null)
                    {
                        agent.service_list = agentServices;
                    }
                }
                return new { merchant, agent };
            }
        }

        public async Task UpdateStore(int merchant_id, MerchantStore store)
        {
            using (var con = new MySqlConnection(_connectionString))
            {
                store.merchant_id = merchant_id;
                string sql;
                if (store.id > 0)
                {
                    store.modified = DateTime.Now;
                    sql = "UPDATE kl_merchant_store set name=@name,address=@address,phone=@phone,modified=@modified where id=@id";
                }
                else
                {
                    store.modified = DateTime.Now;
                    sql = "INSERT kl_merchant_store (merchant_id,name,address,phone,status,modified) values(@merchant_id,@name,@address,@phone,@status,@modified)";
                }

                await con.ExecuteAsync(sql, store);
            }
        }

        public async Task DeleteStore(int merchant_id, int id)
        {
            using (var con = new MySqlConnection(_connectionString))
            {
                const string sql = "DELETE FROM kl_merchant_store WHERE id=@id";
                await con.ExecuteAsync(sql, new { id });
            }
        }

        public async Task<Form> GetActivityStyle(int styleId)
        {
            using (var con = new MySqlConnection(_connectionString))
            {
                const string sql = "SELECT * FROM kl_activity_style where id=@styleId";
                return await con.QueryFirstAsync<Form>(sql, new { styleId });
            }
        }
    }
}